package cn.yo2.irain.log4money.app.item;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.yo2.irain.log4money.app.item.IItemDAO;
import cn.yo2.irain.log4money.app.item.Item;
import cn.yo2.irain.log4money.app.user.UserLogin;

public class ItemDAOImpl extends HibernateDaoSupport implements IItemDAO {

    private static final Log log = LogFactory.getLog(ItemDAOImpl.class);

    public void deleteItem(Item item) throws RuntimeException {
        log.debug("deleting Item instance");
        getHibernateTemplate().delete(item);
        log.debug("delete successful");
    }

    public void saveItem(Item item) throws RuntimeException {
        log.debug("saving Item instance");
        getHibernateTemplate().save(item);
        log.debug("save successful");
    }

    public void updateItem(Item item) throws RuntimeException {
        log.debug("update item ");
        this.getHibernateTemplate().update(item);
        log.debug("update successful");
    }

    public Item findById(String id) {
        log.debug("getting Item instance with id: " + id);
        try {
            Item instance = (Item) this.getHibernateTemplate()
                    .get("cn.yo2.irain.log4money.app.item.Item", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findAll(UserLogin userLogin) throws RuntimeException {

        String hql = "from Item as i where parentItem is null";
        List list = getHibernateTemplate().find(hql);

        return list;
    }

    public List findInItem() {
        return findByProperty("inOut", "0");
    }

    public List findOutItem() {
        return findByProperty("inOut", "1");
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding Item instance with property: " + propertyName
                + ", value: " + value);
        String queryString = "from Item i where i." + propertyName + "='" + value + "'";


        return getHibernateTemplate().find(queryString);
    }

    public Item findByItemName(String itemName) {
        return (Item) findByProperty("itemName", itemName).get(0);
    }

    public List<Item> findByParentId(String parentId, int inout, String ownUser) {
        String hsql = "from Item i where i.parentId = '" + parentId + "' and i.inOut = " + inout + " and i.ownUser = '" + ownUser + "'";
        return getHibernateTemplate().find(hsql);
    }

}
